package com.amiu.autoMybatis;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

/**
 * 
 * @author amiu
 * @version createtime：2017-9-7 下午3:45:16
 */
public class SqlSessionsHelper {
	// private static final Logger logger =
	// Logger.getLogger(SqlSessionsHelperFail.class);
	private MybatisInitialization init = new MybatisInitialization();
	private final SqlSessionFactory sqlSessionFactory;
	private SqlSession sqlSession;
	
	public SqlSessionsHelper(SqlSessionFactory sqlSessionFactory) {
		this.sqlSessionFactory = sqlSessionFactory;
	}

	public SqlSessionsHelper(String scanPackage) {
		init.setBaseScanPackage(scanPackage);
		sqlSessionFactory = init.getSqlSessionFactory();
	}

	public SqlSessionsHelper(String scanPackage, Class<?> annotationClazz) {
		init.setAnnotationClazz(annotationClazz);
		init.setBaseScanPackage(scanPackage);
		sqlSessionFactory = init.getSqlSessionFactory();
	}

	public SqlSession getSqlSession() {
		return sqlSession;
	}
	
	public void openSession() {
		if (isSqlSessionNull()) {
			synchronized (SqlSession.class) {
				if (isSqlSessionNull())
					sqlSession = sqlSessionFactory.openSession();
			}

		}
	}

//	public <T> SqlSession openSession(Class<T> clazz) {
//
//		//sqlSession = sqlSessionFactory.openSession();
//
//		return sqlSession;
//	}

	public void openSession(boolean autoCommit) {
		if (isSqlSessionNull()) {
			synchronized (SqlSession.class) {
				if (isSqlSessionNull())
					sqlSession = sqlSessionFactory.openSession(autoCommit);
			}
		}
	}

	public <T> T getDao(Class<T> clazz) {
//		sqlSession = openSession(clazz);
		if(isSqlSessionNull()) openSession();
		return sqlSession.getMapper(clazz);
	}

	public void commit() {
		if (!isSqlSessionNull()) {
			sqlSession.commit();
		}
	}

	public void close() {
		if (!isSqlSessionNull()) {
			sqlSession.commit();
			sqlSession.close();
		}
	}

	public void rollback() {
		if (!isSqlSessionNull()) {
			sqlSession.rollback();
		}
	}

	boolean isSqlSessionNull() {
		return sqlSession == null;
	}
}
